use chrono::Utc;
use sqlx::SqlitePool;
use crate::error::AppResult;
use crate::models::{User, CreateUser};

/// 根据名称查找用户
pub async fn find_by_name(pool: &SqlitePool, name: &str) -> AppResult<Option<User>> {
    let user = sqlx::query_as::<_, User>(
        "SELECT * FROM user WHERE name = ?"
    )
    .bind(name)
    .fetch_optional(pool)
    .await?;
    
    Ok(user)
}

/// 根据 ID 查找用户
pub async fn find_by_id(pool: &SqlitePool, id: i64) -> AppResult<Option<User>> {
    let user = sqlx::query_as::<_, User>(
        "SELECT * FROM user WHERE id = ?"
    )
    .bind(id)
    .fetch_optional(pool)
    .await?;
    
    Ok(user)
}

/// 创建新用户
pub async fn create(pool: &SqlitePool, create_user: &CreateUser) -> AppResult<User> {
    let now = Utc::now();
    
    let result = sqlx::query(
        "INSERT INTO user (name, email, created_at, updated_at) VALUES (?, ?, ?, ?)"
    )
    .bind(&create_user.name)
    .bind(&create_user.email)
    .bind(now)
    .bind(now)
    .execute(pool)
    .await?;
    
    let user_id = result.last_insert_rowid();
    
    let user = find_by_id(pool, user_id).await?
        .expect("Failed to find newly created user");
    
    Ok(user)
}

/// 查找或创建用户
pub async fn find_or_create(pool: &SqlitePool, name: &str) -> AppResult<User> {
    if let Some(user) = find_by_name(pool, name).await? {
        Ok(user)
    } else {
        create(pool, &CreateUser {
            name: name.to_string(),
            email: None,
        }).await
    }
}
